import * as jwt from 'jsonwebtoken'
import { ResponseUtil } from '../helpers/ResponseUtil'
import { Post } from '../metadata'
import { adminConfig, config } from '../scretConfig'
import { KoaContext } from '../server'

export interface LoginHandlerQueryInter {
  username: string,
  password: string
}

export class LoginController {

  @Post('/login', { query: [], body: ['username:string', 'password:string'] })
  public async login(ctx: KoaContext<{}, LoginHandlerQueryInter>) {
    const { username, password } = ctx.request.body!
    const { username: uname, password: pwd } = adminConfig
    if (username !== uname || password !== pwd) {
      return ResponseUtil.fail(-1, '账号或者密码不正确')
    }
    const expireAt = Date.now() + config.tokenExpiresTime
    const payload = {
      expireAt,
      username
    }
    const token = jwt.sign(payload, config.jwtSecret)
    return ResponseUtil.success({ data: { token, expireAt } })
  }
}

/**
 * 通过校验的函数来检验路由参数
 * @Post("/login", valid(....))
 * login() {
 * }
 */
